package login

import (
	"fmt"
	"net/http"
	"os"
	"strconv"
	"time"

	"../../db/cache"
	"../../db/modes"
	"../../lib"
	"../../router/middleware"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

/*
 * 描述: 创建用户TOKEN
 *
 ***********************************************************************/
func create_token(UId int64, Name string, Phone int64,way int32) (string, error) {
	j := &middleware.JWT{
		[]byte("aldie33!@Dd$$%G&&#asd$^asd&*x%a%……334*"),
	}
	claims := middleware.CustomClaims{
		UId:   UId,   // 用户Id
		Name:  Name,  // 姓名
		Phone: Phone, // 用户手机号
		Way: way,
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix(),                // 签名生效时间
			ExpiresAt: time.Now().Unix() + (24 * 86400), // 过期时间 一天
			Issuer:    "usercenter",                     // 签名的发行者
		},
	}
	return j.CreateToken(claims)
}

/*
 * 描述: 创建用户TOKEN
 *
 *
 ***********************************************************************/
func create_token2(UId, GId, PId, RId int64, Name string, Phone int64) (string, error) {
	j := &middleware.JWT{
		[]byte("aldie33!@Dd$$%G&&#asd$^asd&*x%a%……334*"),
	}
	claims := middleware.CustomClaims{
		UId:   UId,   // 用户Id
		GId:   GId,   // 组ID
		PId:   PId,   // 项目ID
		RId:   RId,   // 角色ID
		Name:  Name,  // 姓名
		Phone: Phone, // 用户手机号
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix(),               // 签名生效时间
			ExpiresAt: time.Now().Unix() + (1 * 86400), // 过期时间 一天
			Issuer:    "crm",                           // 签名的发行者
		},
	}
	return j.CreateToken(claims)
}

/*
 * 描述: 用户登陆
 * 路由: login/login
 * 类型: GET
 *
 ***********************************************************************/
func UserLogin(c *gin.Context) {
	var user modes.StudentInfo

	if c.Query("phone") == "" {
		c.JSON(http.StatusOK, gin.H{"err": 2, "msg": "账号不可为空"})
		return
	}
	user.Phone, _ = strconv.ParseInt(c.Query("phone"), 10, 64)
	if fage, err := user.Get(); nil == err {
		if !fage {
			var chanat modes.ChaNat
			var us modes.Using
			chanat.Phone, _ = strconv.ParseInt(c.Query("phone"), 10, 64)
			//判断首资有没有学员的手机号
			if fage, err = chanat.Get(); err == nil {
				//库存首资手机号插入学员中心
				user.Pass = lib.StrMd5Str(strconv.FormatInt(user.Phone, 10))
				user.File = "file.beijingyuxue.cn/1584588646/3.png"
				user.Name = c.Query("phone")
				user.At = time.Now().Unix()
				user.LastAt = time.Now().Unix()
				user.Coun++
				user.Email = "0"
				user.Address = "0"
				user.Start = 0
				if !fage {
					//判断库存有没有学员的手机号
					us.Phone, _ = strconv.ParseInt(c.Query("phone"), 10, 64)
					fage, _ = us.Get()
					if !fage {
						c.JSON(http.StatusOK, gin.H{"err": 2, "msg": "该账号还没有被注册，请注册"})
						return
					} else {

						if _, err = user.Save(); nil != err {
							c.JSON(http.StatusOK, gin.H{"err": 2, "msg": err.Error()})
							return
						}
						token, _ := create_token(user.Id, user.Name, user.Phone,int32(1))
						c.JSON(http.StatusOK, gin.H{"err": 0, "token": token, "info": user})
						return
					}
				} else {
					if _, err = user.Save(); nil != err {
						c.JSON(http.StatusOK, gin.H{"err": 2, "msg": err.Error()})
						return
					}
					token, _ := create_token(user.Id, user.Name, user.Phone,int32(1))
					c.JSON(http.StatusOK, gin.H{"err": 0, "token": token, "info": user})
					return
				}
			}
			c.JSON(http.StatusOK, gin.H{"err": 2, "msg": "该账号还没有被注册，请注册"})
			return
		}
	} else {
		c.JSON(http.StatusOK, gin.H{"err": 1, "msg": err.Error()})
		return
	}
	if user.Pass != c.Query("pass") {
		c.JSON(http.StatusOK, gin.H{"err": 1, "msg": "密码不正确"})
		return
	}
	user.Coun++
	user.LastAt = time.Now().Unix()
	user.IdSet("coun,last_at")
	token, _ := create_token(user.Id, user.Name, user.Phone,int32(1))
	c.JSON(http.StatusOK, gin.H{"err": 0, "token": token, "info": user})
}

/*
 * 描述: 授权点播
 *
 ***********************************************************************/
func AuthorVideo(c *gin.Context) {
	var repost lib.AutoGenerated
	var val cache.VideoCode
	//vid := c.PostForm( "vid" )
	code := c.PostForm("verificationcode")
	if resu, err := val.Get(code); err == nil {
		if resu == "" {
			println("验证码过期")
			c.JSON(http.StatusOK, gin.H{"err": 2, "msg": "验证码已过期"})
			return
		}
		println("redis 有误")
	}
	println("返回正常")
	repost.Response.Version = fmt.Sprintf("%d", 1)
	repost.Response.Enable = 1
	repost.Response.Freetime = 120
	repost.Response.Message = "欢迎观看！"
	repost.Response.Callback = ""
	repost.Marquee.Loop = -1
	repost.Marquee.Type = "text/image"
	repost.Marquee.Text.Content = ""
	repost.Marquee.Text.FontSize = 20
	repost.Marquee.Text.Color = "0xffffff"
	repost.Marquee.Image.ImageURL = "http://abc.jpg"
	repost.Marquee.Image.Width = 300
	repost.Marquee.Image.Height = 22
	repost.Marquee.Action.Start.Xpos = 0.312
	repost.Marquee.Action.Start.Ypos = 0.423
	repost.Marquee.Action.Start.Alpha = 0.8
	repost.Marquee.Action.End.Xpos = 0.312
	repost.Marquee.Action.End.Ypos = 0.823
	repost.Marquee.Action.End.Alpha = 0.8
	//fmt.Println(repost)
	c.JSON(http.StatusOK, repost)
}

func ClassBegins(c *gin.Context) {
	var uc modes.Class
	var teachClass modes.TeachClass
	var cl modes.SClass
	var em modes.Employee
	var crs modes.CrmStuden
	uc.Phone, _ = strconv.ParseInt(c.Query("phone"), 10, 64) //请输入手机
	uc.Cid, _ = strconv.ParseInt(c.Query("cid"), 10, 64)     //班型id
	usid := c.Query("usid")                                  //坐席工号
	fmt.Println("手机号", uc.Phone)                             //手机号
	fmt.Println("班型", uc.Cid)                                //班型
	cl.Id = uc.Cid
	cl.Get() //取班型名称      GetName
	teachClass.Get()

	if fage, err := uc.Get(); nil == err {
		if fage {
			c.JSON(http.StatusOK, gin.H{"err": 1, "msg": "已经开课"})
			return
		}
	}
	uc.CName = cl.Name
	if c.Query("order_no") != "" {
		uc.OrderNo = c.Query("order_no")
	} else {
		uc.OrderNo = "0"
	}
	uc.At = time.Now().Unix()
	uc.CloseAt = time.Now().AddDate(0, cl.ValidTerm,0 ).Unix()

	if _, err := uc.Save(); nil != err {
		c.JSON(http.StatusOK, gin.H{"err": 2, "msg": "未开课成功"})
		return
	}
	em.GetName(usid)
	crs.Weight = 0
	crs.Phone = strconv.FormatInt(uc.Phone, 10) //手机号
	crs.Amount = 0
	crs.Name = "0"
	crs.Senior = 0
	crs.Uid = em.Id
	crs.Uname = em.Name
	crs.Uat = time.Now().Unix()
	crs.OrderId = 0
	crs.Cnumber = 0
	crs.Cat = 0
	crs.Note = "0"
	if _, err := crs.Save(); nil != err {
		c.JSON(http.StatusOK, gin.H{"err": 3, "msg": "crm_studen" + "手机号重复"})
		fmt.Println("错误", err.Error())
		return
	}
	var us modes.StudentInfo
	us.Phone = uc.Phone
	if fage, err := us.Get(); nil == err {
		if fage {
			c.JSON(http.StatusOK, gin.H{"err": 1, "msg": "账号已经存在"})
			return
		} else {
			us.Pass = lib.StrMd5Str(strconv.FormatInt(us.Phone, 10))
			us.Name = strconv.FormatInt(us.Phone, 10)
			us.At = time.Now().Unix()
			us.LastAt = time.Now().Unix()
			us.Coun = 0
			us.Email = "0"
			us.Address = "0"
			us.Start = 0
			if _, err = us.Save(); nil != err {
				c.JSON(http.StatusOK, gin.H{"err": 2, "msg": err.Error()})
				return
			}
		}
	}
	c.JSON(http.StatusOK, gin.H{"err": 0, "msg": "开课成功"})
}

func BuildPager(c *gin.Context, page *modes.Pager) {
	page.Count, _ = strconv.Atoi(c.PostForm("count")) // 单页数量
	page.Page, _ = strconv.Atoi(c.PostForm("page"))   // 页码
	page.Coll, _ = strconv.Atoi(c.PostForm("coll"))   // 排序字段
	page.Rules, _ = strconv.Atoi(c.PostForm("rule"))  // 排序规则
}

func EmployList(c *gin.Context) {

	var employ modes.Employee
	var page modes.Pager
	BuildPager(c, &page)
	employ.Name = c.PostForm("name")
	if err := c.PostForm("name"); err == "" {
		c.JSON(http.StatusOK, gin.H{"err": 2, "msg": "用戶名不能为空"})
		return
	}
	err := employ.GetListByName(&page)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"err": 3, "msg": "获取信息失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"err": 0, "list": page})
	return

}

/*
	身份证信息认证
*/

func Cradnd(c *gin.Context) {
	var car lib.CardCode
	name := c.Query("name")
	card := c.Query("card")
	res, _ := lib.IsIdCard(card)
	var info string
	if res {
		info, msgss, _ := car.OutbQuery(name, card)
		if info != "1" {
			c.JSON(http.StatusOK, gin.H{"err": 0, "msg": "失败", "data": info})
			return
		}
		c.JSON(http.StatusOK, gin.H{"err": 1, "msg": msgss, "data": info})
		return
	}
	c.JSON(http.StatusOK, gin.H{"err": 2, "msg": "失败", "data": info})
}


//七牛上传文件
func PngUpl(c *gin.Context) {
	var qiniu lib.QiNiu
	var impile string
	files, err := c.FormFile("upload")
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"err": 1, "msg": "请上传文件"})
		return
	}
	impile = fmt.Sprintf("%d_%s", time.Now().Unix(), files.Filename)
	if err := c.SaveUploadedFile(files, impile); err != nil {
		c.JSON(http.StatusOK, gin.H{"err": 1, "msg": err.Error()})
		return
	}
	url := qiniu.PngUpload(impile)
	fmt.Println(url)
	os.Remove(impile)
	c.JSON(http.StatusOK, gin.H{"err": 0, "msg": url})
}

func NumberTel(c *gin.Context) {
	var val cache.NumberTel
	val.Phone = c.Query("phone")
	if err := val.Set(); err != nil {
		c.JSON(http.StatusOK, gin.H{"err": 1, "msg": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"err": 0, "msg": "设置成功"})
}

func NumberTelGet(c *gin.Context) {
	var val cache.NumberTel
	err := val.Get()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"err": 1, "msg": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"err": 0, "msg": val})
}
